<!DOCTYPE html>
<html lang="zh">
  <head>
    <title>松果网</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="http://cdnjs.bootcss.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet">
	<link href="http://cdnjs.bootcss.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap-responsive.min.css" rel="stylesheet">
	<link href="http://tarruda.github.com/bootstrap-datetimepicker/assets/css/bootstrap-datetimepicker.min.css" rel="stylesheet">
    <link href="css/main.css" rel="stylesheet">
  </head>
  <body>
    <div class="navbar navbar-inverse navbar-fixed-top">
      <div class="navbar-inner">
        <div class="container">
          <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="brand" href="#">松果网</a>
          <div class="nav-collapse collapse">
            <ul class="nav">
              <li><a href="activation.jsp">激活设备</a></li>
              <li><a href="j_spring_security_logout">退出</a></li>
            </ul>
          </div>
        </div>
      </div>
    </div>
	<header class="jumbotron subhead">
  	  <div class="container">
    	<h1>管理控制台</h1>
    	<p id="identity" class="lead"></p>
      </div>
	</header>
	<div id="editModel" class="modal hide fade">
  	  <div class="modal-header">
    	<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    	<h3>修改设备</h3>
  	  </div>
  	  <div class="modal-body"><form id="editDevice" method="post" action="#">
		<div class="input-prepend">
		  <span class="add-on"><i class="icon-pencil"></i></span> 
		  <input type="text" id="devicename" class="input-xlarge" name="devicename" placeholder="设备名称">
		</div>
  	  </div>
  	  <div class="modal-footer">
    	<button type="submit" class="btn btn-success">确定</button></form>
    	<button class="btn btn-success" data-dismiss="modal" aria-hidden="true">取消</button>
  	  </div>
	</div>
	<div id="deleteModel" class="modal hide fade">
  	  <div class="modal-header">
    	<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    	<h3>删除设备</h3>
  	  </div>
  	  <div class="modal-body">
  	    <p>确定删除吗？</p>
  	  </div>
  	  <div class="modal-footer">
    	<button id="deleteDevice" class="btn btn-success">确定</button>
    	<button class="btn btn-success" data-dismiss="modal" aria-hidden="true">取消</button>
  	  </div>
	</div>
	<div id="queryModel" class="modal hide fade">
  	  <div class="modal-header">
    	<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    	<h3>数据查询</h3>
  	  </div>
  	  <div class="modal-body"><form id="queryData" method="post" action="#">
  	    <div id="startTime" class="input-prepend date">
		  <span class="add-on"><i data-time-icon="icon-time" data-date-icon="icon-calendar"></i></span>
		  <input type="text" id="starttime" class="input-xlarge" name="starttime" placeholder="起始时间"></input>
    	</div>
    	<div id="endTime" class="input-prepend date">
		  <span class="add-on"><i data-time-icon="icon-time" data-date-icon="icon-calendar"></i></span>
		  <input type="text" id="endtime" class="input-xlarge" name="endtime" placeholder="结束时间"></input>
    	</div>
  	  </div>
  	  <div class="modal-footer">
    	<button type="submit" class="btn btn-success">查询</button></form>
    	<button class="btn btn-success" data-dismiss="modal" aria-hidden="true">取消</button>
  	  </div>
	</div>
    <div class="container">
  	  <div class="marketing">
    	<h1>设备管理</h1>
    	<p class="marketing-byline">探索未知的智能世界，感知数据的力量!</p>
    	<p id="selectedCode" class="hide"></p>
    	<div class="row-fluid">
      	  <div id="map_canvas"></div>
        </div>
      </div>
    </div>
    <footer class="footer">
      <div class="container">
        <p>&copy; 2013 北京松果科技有限公司</p>
        <ul class="footer-links">
          <li><a href="#">关于我们</a></li>
          <li class="muted">·</li>
          <li><a href="#">在线帮助</a></li>
          <li class="muted">·</li>
          <li><a href="#">隐私条款</a></li>
          <li class="muted">·</li>
          <li><a href="#">用户协议</a></li>
        </ul>
        <p><a href="http://www.miitbeian.gov.cn/" target="_blank">京ICP备13022507号</a></p>
      </div>
    </footer>
	<script src="http://cdnjs.bootcss.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="http://cdnjs.bootcss.com/ajax/libs/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
	<script src="http://tarruda.github.com/bootstrap-datetimepicker/assets/js/bootstrap-datetimepicker.min.js"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
	<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/localization/messages_zh.js"></script>
    <script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyBKkEdoXQxDyl3OKTnMjkvRX-HzOxmsxi8&sensor=false"></script>
    <script src="js/jquery.gomap-1.3.2.min.js"></script>
    <script src="js/additional-methods.js"></script>
	<script src="js/localization/messages_zh.js"></script>
    <script src="js/jquery.scrollUp.min.js"></script>
    <script src="js/jquery.html5storage.min.js"></script>
    <script src="js/markerclusterer.min.js"></script>
    <script src="js/mqttws31.js"></script>
    <script src="js/main.js"></script>
    <script type="text/javascript">
      
    	var client;
    	
    	$(document).ready(function() {
    	
			$.scrollUp({
				scrollName: 'scrollUp', 
	    		topDistance: '300', 
	    		topSpeed: 300, 
	    		animation: 'fade', 
	    		animationInSpeed: 200, 
	    		animationOutSpeed: 200, 
	    		scrollText: '', 
	    		activeOverlay: false 
			});
			
			$("#startTime").datetimepicker({
				format: "yyyy-MM-dd hh:mm:ss",
				language: "zh"
			});
			
			$("#endTime").datetimepicker({
				format: "yyyy-MM-dd hh:mm:ss",
				language: "zh"
			});
			
			$("#queryData").validate({
				rules : {
					starttime : {
						required : true,
						soonerThan : "#endtime"
					},
					endtime : {
						required : true,
						laterThan : "#starttime"
					}
				},
				submitHandler : function() { 
					// need to modify
					getHistory("hello", new Date($("#starttime").val()), new Date($("#endtime").val()));
		        }
			});
			
			$("#editDevice").validate({
				rules : {
					devicename : {
						required : true
					}
				},
				submitHandler : function() {
					$("#editModel").modal("hide");
					getDeviceId($("#selectedCode").text(), updateDevice);
		        }
			});
			
			$("#deleteDevice").on("click", function() {
				$("#deleteModel").modal("hide");
				getDeviceId($("#selectedCode").text(), deleteDevice);
			});
			
			$("#identity").text("欢迎" + $.sessionStorage.getItem("username") + "，开始管理你的设备吧！");
			
			$("#map_canvas").goMap({
				latitude: 39.905841, 
		        longitude: 116.391596, 
		        zoom: 8,
				maptype: 'ROADMAP',
				hideByClick: false
			});
			
			$.goMap.ready(function() {
				var clientId = $.sessionStorage.getItem("username") + "@pinecone.cc";
				client = new Messaging.Client("www.pinecone.cc", Number("61614"), clientId);
				client.onMessageArrived = onMessageArrived;           
			    client.connect({onSuccess:onConnect, onFailure:onFailure}); 
			});
	
		});
    	
    	function onConnect(frame) {
    		getUserId(new MarkerClusterer($.goMap.map));
    	}
    	
    	function onFailure(failure) {
    		getUserId(new MarkerClusterer($.goMap.map));
    		alert(failure.errorMessage);
    	}
    	
    	function onMessageArrived(message) {
    		alert(message.payloadString);
    	}
    	
    	function getHistory(id, start, end) {
    		$.ajax({
		    	type : "GET",
		    	url : "rest/m/history/" + id + "/" + start.format("yyyy-MM-dd hh:mm:ss"),
		    	username : $.sessionStorage.getItem("username"),
		    	password : $.sessionStorage.getItem("password"),
		    	success : function(data) {
		    		alert(start.format("yyyy-MM-dd hh:mm:ss") + " --- " + data); // need to remove
		    		start.setSeconds(start.getSeconds() + 1);
		    		if(start <= end) getHistory(id, start, end);
		    	}
			});
    	}
    	
    	function updateDevice(id) {
    		$.ajax({
		    	type : "PUT",
		    	url : "rest/device/" + id,
		    	contentType : "application/json; charset=utf-8",
		    	data : "{\"name\":\"" + $("#devicename").val() + "\"}",
		    	username : $.sessionStorage.getItem("username"),
		    	password : $.sessionStorage.getItem("password")
			});
    	}
    	
    	function deleteDevice(id) {
    		$.ajax({
		    	type : "DELETE",
		    	url : "rest/device/" + id,
		    	username : $.sessionStorage.getItem("username"),
		    	password : $.sessionStorage.getItem("password")
			});
    	}
    	
    	function getUserId(markerClusterer) {
    		$.ajax({
		    	type : "GET",
		    	url : "rest/user/search/names?name=" + $.sessionStorage.getItem("username"),
		    	dataType : "json",
		    	username : $.sessionStorage.getItem("username"),
		    	password : $.sessionStorage.getItem("password"),
		    	success : function(data) {
		    		var href = data.results[0]._links[2].href;
		    		getDevicesByUserId(markerClusterer, href.substring(href.lastIndexOf("/") + 1));
		    	}
			});
    	}
    	
    	function getDevicesByUserId(markerClusterer, id) {
    		$.sessionStorage.setItem("userId", id);
    		$.ajax({
	    		type : "GET",
	    		url : "rest/user/" + id + "/devices",
	    		dataType : "json",
	    		username : $.sessionStorage.getItem("username"),
	    		password : $.sessionStorage.getItem("password"),
	    		success : function(data) {
	    			var links = data._links;
	    			if(links.length > 0) {
	    				for(var i = 0; i < links.length; i++) {
	    					getDeviceById(markerClusterer, links[i].href);
	    				}	    				
	    			}
	    		}
			});
    	}
    	
    	function getDeviceById(markerClusterer, url) {
    		$.ajax({
	    		type : "GET",
	    		url : url,
	    		dataType : "json",
	    		username : $.sessionStorage.getItem("username"),
	    		password : $.sessionStorage.getItem("password"),
	    		success : function(data) {
	    			addDeviceToMap(markerClusterer, data.latitude, data.longitude, data.name, data.code);
	    		}
			});
    	}

    	function addDeviceToMap(markerClusterer, latitude, longitude, name, code) { 
    		$("#map_canvas").before(
    			'<div id="info_' + code + '" class="hide">'+
    				'<p>' + name + '</p>'+
    				'<ul class="nav nav-pills">'+
    					'<li><a data-toggle="modal" data-target="#editModel"><i class="icon-edit"></i> 修改</a></li>'+
    					'<li><a data-toggle="modal" data-target="#deleteModel"><i class="icon-remove"></i> 删除</a></li>'+ 
    				'</ul>'+
    				'<table id="' + code + '" class="table table-hover">'+
    					'<tbody></tbody>'+
    				'</table>'+
    			'</div>'
    		);
    		$.goMap.createMarker({  
    			id: code,
            	latitude: latitude, 
            	longitude: longitude, 
                title: name,
                html: {
                	id: '#info_' + code
                }
            });  
    		$.goMap.createListener({type:'marker', marker:code}, 'click', function() { 
    			$("#selectedCode").text(code);
    			//start mqtt client
    			setTimeout("refresh('"+code+"')",2000);
    	    }); 
    		getDeviceId(code, getVariablesByDeviceId);  
    		markerClusterer.addMarker($($.goMap.mapId).data(code));
    		client.subscribe("pinecone@device." + code);
    	}
    	
    	function getDeviceId(code, callback) {
    		$.ajax({
		    	type : "GET",
		    	url : "rest/device/search/codes?code=" + code,
		    	dataType : "json",
		    	username : $.sessionStorage.getItem("username"),
		    	password : $.sessionStorage.getItem("password"),
		    	success : function(data) {
		    		var href = data.results[0]._links[2].href;
		    		callback(href.substring(href.lastIndexOf("/") + 1), code);
		    	}
			});
    	}
    	
    	function getVariablesByDeviceId(id, code) {
    		$.ajax({
	    		type : "GET",
	    		url : "rest/device/" + id + "/variables",
	    		dataType : "json",
	    		username : $.sessionStorage.getItem("username"),
	    		password : $.sessionStorage.getItem("password"),
	    		success : function(data) {
	    			var links = data._links;
	    			if(links.length > 0) {
	    				for(var i = 0; i < links.length; i++) {
	    					getVariableById(links[i].href, code);
	    				}	    				
	    			}
	    		}
			});
    	}
    	
    	function getVariableById(url, code) {
    		$.ajax({
	    		type : "GET",
	    		url : url,
	    		dataType : "json",
	    		username : $.sessionStorage.getItem("username"),
	    		password : $.sessionStorage.getItem("password"),
	    		success : function(data) {
	    			var href = data._links[2].href;
	    			var varid = href.substring(href.lastIndexOf("/") + 1);
	    			$("#" + code + " tbody").append(
	    				'<tr><td>' + data.name + '</td><td id='+varid+'><td>'+  
	    				'<a data-toggle="modal" data-target="#queryModel"><i class="icon-search"></i> 查询 </a>'+
	            		'<a href="#"><i class="icon-wrench"></i> 设置</a>'+
	            		'</td></tr>'
	            	);	
	    		}
			});
    	}
    	
    	function refresh(code){
    		$.ajax({
    	 		url:'rest/m/channel/subscribe', 
    	 		type: 'POST',
    	 		data: {code:code}, 
    			timeout: 1000,
    			cache: false,
    	 		error: function(XMLHttpRequest, textStatus, errorThrown){
    	 			setTimeout("refresh('"+code+"')",10000);
    	 		}, 
    	 		success: function(result){
    	 			isConnected = true;
    	 			var obj = eval('(' + result + ')'); 
    	 			jsonObject = obj;
    	 			
    	 			$("td[id="+obj.id+"]").text(obj.value);
    	 			
    	 			setTimeout("refresh('"+code+"')",10000);
    	 		} 
    	 	});
    	}
    	
    </script>
  </body>
</html>